let requestCompleteHandlers = [];
let requestLoadingCount = 0;//显示loading的次数，用户判定何时hideLoading
module.exports = {
  /**
   * Make request with session info
   * @param obj Object url, method, data, success, fail
   */
  request: function(obj) {
    let userinfo = getApp().getUserinfo(), currentCity = getApp().getCurrentCity();
    obj.header = obj.header || {};
    obj.header.cityid = currentCity.id;
    if(userinfo) {
      obj.header.token = userinfo.token;
    }
    if(!/^http/.test(obj.url)) {
      obj.url = getApp().globalData.apiBaseUri + (/^\//.test(obj.url)?obj.url:'/'+obj.url);
    }
    let successCall = obj.success;
    let failCall = obj.fail;
    obj.success = function(res) {
      if(typeof res.data !== 'object' || res.data.code!==1) {
        // 如果响应内容非json 或code不为1， 视为失败
        obj.fail(res);
        return;
      }
      if (typeof successCall === 'function') {
        setTimeout(()=>{
          successCall(res.data, res);
        },1);

      }
    };
    obj.fail = function (res) {
      setTimeout(()=>{
        let showMsg = true;
        if (typeof failCall === 'function') {
          showMsg = failCall(res.data, res);
        }
        if(showMsg!==false) {
          wx.showToast({'title': (res.data?res.data.msg||'网络错误':'网络错误'), icon:"none"})
        }
      },1);
    };
    obj.complete = function(res) {
      if(obj.loading!==false) {
        if(--requestLoadingCount<=0) {
          requestLoadingCount = 0;
          wx.hideLoading();
        }

      }
      for(let i in requestCompleteHandlers) {
        if(typeof requestCompleteHandlers[i] === 'function') {
          requestCompleteHandlers[i].apply(this, [res.data, res]);
        }
      }
    };
    if(obj.loading!==false) {
      //转菊花，遮蔽操作
      requestLoadingCount++;
      wx.showLoading({title:'',mask:true});
    }
    return wx.request(obj);
  },
  // 发起GET
  get: function(obj) {
    obj.method = 'GET';
    return this.request(obj);
  },
  // 发起POST
  post: function(obj) {
    obj.method = 'POST';
    return this.request(obj);
  },
  //
  onRequestComplete: function(fn) {
    for(let i in requestCompleteHandlers) {
      if(requestCompleteHandlers[i]===fn) {
        //已经有同一个实例, 退出
        return;
      }
    }
    requestCompleteHandlers.push(fn);
  },
  // uploadFile obj.filePath[required]
  // obj.header[optional], obj.success[optional], obj.fail[optional]
  // return res.data.data.url
  uploadFile: function(obj) {
    // obj = Object.assign({url: '/common/upload_qiniu', name: 'file'}, obj);
    // let userinfo = getApp().getUserinfo();
    // if(userinfo) {
    //   obj.header ? obj.header.token = userinfo.token : obj.header = {token: userinfo.token};
    // }
    let tempFilePath = obj.filePath;
    let successCb = obj.success;
    let failCb = obj.fail;
    wx.getFileInfo({
      filePath:tempFilePath,
      success: res => {
        if(getApp().globalData.uploadOssStatus){
          let size = res.size;
          let md5 = res.digest;
          let nameParts = tempFilePath.split('.');
          let suffix = nameParts[nameParts.length-1];
          this.post({
            url: getApp().globalData.apiBaseUri + '/xilujob.common/params',
            data: {md5:md5, name:'nouse.'+suffix},
            success: (ret, response) => {
              //拿到签名，直传alioss
              let key = ret.data.key;//存储路径
              wx.uploadFile({
                name: 'file',
                filePath: tempFilePath,
                formData:{
                  key: ret.data.key,
                  OSSAccessKeyId: ret.data.id,
                  success_action_status: 200,
                  policy: ret.data.policy,
                  signature: ret.data.signature
                },
                url: getApp().globalData.alioss.endpoint,
                success: res => {
                  if(res.statusCode!==200) {
                    if(typeof failCb==='function') {
                      res.data = {code:0, msg: '上传阿里云OSS失败'};
                      failCb(res.data, res);
                    }else {
                      wx.showToast({'title':"上传阿里云OSS失败",icon:"none"})
                    }
                    return;
                  }
                  res.data = {code:1, data:{url:'/'+key}};
                  successCb(res.data, res);
                },
                fail: (res) => {
                  if(typeof failCb==='function') {
                    res.data = {code:0, msg: '上传阿里云OSS失败'};
                    failCb(res.data, res);
                  }else {
                    wx.showToast({'title':"上传阿里云OSS失败",icon:"none"})
                  }
                }
              });
            },
            fail: (ret, response) => {
              if(typeof failCb==='function') {
                return failCb(ret, response);
              }
            }
          });
        }else{
          wx.uploadFile({
            name: 'file',
            filePath: tempFilePath,
            formData:{
            
            },
            url: getApp().globalData.apiBaseUri+'/common/upload',
            success: res => {
              if(res.statusCode!==200) {
                if(typeof failCb==='function') {
                  res.data = {code:0, msg: '上传失败'};
                  failCb(res.data, res);
                }else {
                  wx.showToast({'title':"上传失败",icon:"none"})
                }
                return;
              }
              let data = JSON.parse(res.data)
              data = {code:1, data:{url:data.data.fullurl}};
              successCb(data, res);
            },
            fail: (res) => {
              if(typeof failCb==='function') {
                res.data = {code:0, msg: '上传失败'};
                failCb(res.data, res);
              }else {
                wx.showToast({'title':"上传失败",icon:"none"})
              }
            }
          });
        }
      }
    });
  },
  // 获取缓存数据
  getCache: function (key, defaultValue) {
    let timestampNow = +new Date() / 1e3, result = "";
    timestampNow = parseInt(timestampNow);
    try {
      (result = wx.getStorageSync(key + getApp().globalData.appid)).expire > timestampNow || 0 == result.expire ? result = result.value : (result = "",
        this.removeCache(key));
    } catch (e) {
      result = void 0 === defaultValue ? "" : defaultValue;
    }
    return result || defaultValue;
  },
  // 设置缓存数据
  setCache: function (key, value, expireInSeconds) {
    let timestampNow = +new Date() / 1e3,
      result = true,
      a = {
        expire: expireInSeconds ? timestampNow + parseInt(expireInSeconds) : 0,
        value: value
      };
    try {
      wx.setStorageSync(key + getApp().globalData.appid, a);
    } catch (e) {
      result = false;
    }
    return result;
  },
  // 移除缓存数据
  removeCache: function (key) {
    let result = true;
    try {
      wx.removeStorageSync(key + getApp().globalData.appid);
    } catch (e) {
      result = false;
    }
    return result;
  },
};
